package com.ny.maipiao;

import java.util.Scanner;

public class Piao {
    private int pzs = 100;
    private final Object suo = new Object();

    public void maiPiao() {
        Scanner input = new Scanner(System.in);

        synchronized (suo) {
            System.out.print(Thread.currentThread().getName() + " 当前余票：" + pzs + "，请输入购买数量：");
            int shuLiang = input.nextInt();

            if (shuLiang <= 0) {
                System.out.println("！数量无效");
            } else if (pzs >= shuLiang) {
                pzs -= shuLiang;
                System.out.println(Thread.currentThread().getName() + " 成功售出" + shuLiang + "张，剩余：" + pzs);
            } else {
                System.out.println("！余票不足，仅剩" + pzs + "张");
            }
        }
    }

    public static void main(String[] args) {
        Piao p = new Piao();

        for (int i = 1; i <= 2; i++) {
            new Thread(() -> {
                while (p.pzs > 0) {
                    p.maiPiao();
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + " 票已售完");
            }, "窗口" + i).start();
        }
    }
}
